
#include "Enemy.h"
#include "Waypoint.h"
#include "EventSystem.h"
#include "../../SGD Wrappers/CSGD_TextureManager.h"


//Constructor
Enemy::Enemy(void)
{
	this->x					= 0.0f;
	this->y					= 0.0f;
	this->velocityX			= 0.0f;
	this->velocityY			= 0.0f;
	this->rotation			= 0.0f;
	this->collisionRadius	= 1.0f;
	this->isAlive			= true;
	this->entityType		= ENTITY_ENEMY;
	this->enemyType			= ENEMY_BASIC;
	this->moveSpeed			= 120.0f;
	this->healthCurrent		= 50;
	this->healthMax			= 50;
	this->debuffSlow		= false;
	this->debuffPoison		= false;
	this->currentWaypoint	= nullptr;
	this->textureID = CSGD_TextureManager::GetInstance()->LoadTexture(_T("../Resource/Graphics/PlaceholderImage.png"));
}


//Destructor
Enemy::~Enemy(void)
{
}


//Update
void Enemy::Update(float dt)
{
	//Switch to next waypoint
	if (currentWaypoint != nullptr &&
		(sqrt((currentWaypoint->x - x)*(currentWaypoint->x - x) + (currentWaypoint->y - y)*(currentWaypoint->y - y))) <= 5.0f)
	{
		currentWaypoint = currentWaypoint->next;
	}

	//Move toward current waypoint
	if (currentWaypoint != nullptr)
	{
		float vectorToTargetX = currentWaypoint->x - x;
		float vectorToTargetY = currentWaypoint->y - y;
		float vectorLength    = sqrt(vectorToTargetX*vectorToTargetX + vectorToTargetY*vectorToTargetY);
		x += (vectorToTargetX / vectorLength) * moveSpeed * dt;
		y += (vectorToTargetY / vectorLength) * moveSpeed * dt;
	}

	//Reached the end of the path
	if (currentWaypoint == nullptr)
	{
		EventSystem::GetInstance()->SendEvent("ENEMY_HIT_BASE",nullptr,nullptr,nullptr);
		isAlive = false;
	}

	//Set rotation
	if (currentWaypoint != nullptr)
	{
		float newRotation = rotation;
		float vectorToTargetX = currentWaypoint->x - x;
		float vectorToTargetY = currentWaypoint->y - y;
		newRotation = atan2(vectorToTargetY, vectorToTargetX) + 3.141f * 0.5f;
		if (newRotation >  6.283f) newRotation -= 6.281f;
		if (newRotation < -0.001f) newRotation += 6.281f;
		float rotationRate = 8.0f * dt;
		if (rotation - newRotation < -0.001f)
		{
			if (fabs(rotation - newRotation) > 3.141f) rotation -= rotationRate;
			else rotation += rotationRate;
		}
		if (rotation - newRotation >  0.001f)
		{
			if (fabs(rotation - newRotation) > 3.141f) rotation += rotationRate;
			else rotation -= rotationRate;
		}
		if (rotation >  6.283f) rotation -= 6.281f;
		if (rotation < -0.001f) rotation += 6.281f;
	}
}


//Render
void Enemy::Render()
{
	CSGD_TextureManager* TM = CSGD_TextureManager::GetInstance();
	RECT rect = {0, 0, 64, 64};
	POINT ptCenter = { (rect.right - rect.left) / 2, (rect.bottom - rect.top) / 2 };
	TM->Draw(textureID, (int)x - ptCenter.x, (int)y - ptCenter.y, 1.0f, 1.0f, &rect,
		(float)ptCenter.x, (float)ptCenter.y, rotation, D3DCOLOR_ARGB(255,255,255,255));

	TM->Draw(textureID, (int)x-3, (int)y-3, 0.1f, 0.1f, &rect, 32.0f, 32.0f, rotation, D3DCOLOR_ARGB(255,255,50,50));
}


//Take damage
void Enemy::TakeDamage(int damage)
{
	healthCurrent -= damage;
	if (healthCurrent <= 0)
	{
		isAlive = false;
	}
}
